package com.zoro.barn.business.service.sqldocument.business.document.controller;

import com.zoro.barn.business.service.sqldocument.conf.MongoDbConfig;
import com.zoro.barn.commons.mongodb.dao.MongoDao;
import com.zoro.barn.commons.webcommons.tools.WebContentUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.Part;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhaoxingwu
 */
@RestController
@RequestMapping("document-upload")
public class FileUploadController {

    private final MongoDbConfig mongoDbConfig;
    private final MongoDao mongoDao;

    public FileUploadController(MongoDbConfig mongoDbConfig, MongoDao mongoDao) {
        this.mongoDbConfig = mongoDbConfig;
        this.mongoDao = mongoDao;
    }

    @RequestMapping("/image")
    public Map<String, String> image() throws ServletException, IOException {
        HttpServletRequest req = WebContentUtil.getRequest();
        Collection<Part> parts = req.getParts();
        Map<String, String> result = new HashMap<>();
        for (Part p : parts) {
            String fileName = p.getSubmittedFileName();
            InputStream is = p.getInputStream();
            String id = mongoDao.upload(mongoDbConfig.getDocumentImageDb(), is, fileName, null, "");
            result.put(fileName, id);
        }
        return result;
    }
}
